﻿using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip;

namespace GptChatBatch.WinUI.Tests
{
    public partial class TestForm1 : Form
    {
        public TestForm1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string fileDir = @"E:\工作区-文档\项目2023-正思考-心理-头条号运营\文章\5月28日\";            
            if (!Directory.Exists(fileDir)) return;
            string[] filePathList = Directory.GetFiles(fileDir, "*.txt");
            foreach(string filePath in filePathList)
            {
                writeLine(filePath);
            }

            return;

            string cookies = "passport_csrf_token=e73eb7247b72c50cf8fb8525aa4fafb2; passport_csrf_token_default=e73eb7247b72c50cf8fb8525aa4fafb2; s_v_web_id=verify_li1pwion_XwG0usZG_b9YA_4uPK_8k2L_RU3gyubLV3y4; _ba=BA0.2-20230524-5110e-3tMB9zozwLQSxZjQfFVx; d_ticket=c8e9c1e2ff2fceaa09002a3b402077a644fac; n_mh=4ZPAsLHacJwTtvJyaysKitsreCsb0LhrhfvRYdwbscM; sso_auth_status=03303e391c238bc67e8cc6e4fb591dd1; sso_auth_status_ss=03303e391c238bc67e8cc6e4fb591dd1; sso_uid_tt=b617f3025557af16309989f19e52b216; sso_uid_tt_ss=b617f3025557af16309989f19e52b216; toutiao_sso_user=5181c275b2d91edbddb3f7369ce4fb5e; toutiao_sso_user_ss=5181c275b2d91edbddb3f7369ce4fb5e; sid_ucp_sso_v1=1.0.0-KGJkMWNmOTJiZjcxY2EwOTZmZDg5MmYxYThjODdjNmFiY2UxNDNlMjQKHwjOp_CHgvTGBBCvl7ijBhjPCSAMMOKfiOgFOAJA8QcaAmxmIiA1MTgxYzI3NWIyZDkxZWRiZGRiM2Y3MzY5Y2U0ZmI1ZQ; ssid_ucp_sso_v1=1.0.0-KGJkMWNmOTJiZjcxY2EwOTZmZDg5MmYxYThjODdjNmFiY2UxNDNlMjQKHwjOp_CHgvTGBBCvl7ijBhjPCSAMMOKfiOgFOAJA8QcaAmxmIiA1MTgxYzI3NWIyZDkxZWRiZGRiM2Y3MzY5Y2U0ZmI1ZQ; passport_auth_status=d151625f27ddf9ca6157d1afbc9563d6%2C2afdf20edd3170c50a87c74956d15ea0; passport_auth_status_ss=d151625f27ddf9ca6157d1afbc9563d6%2C2afdf20edd3170c50a87c74956d15ea0; sid_guard=f2d61b706ab7edbebfbe94465cbb185a%7C1684933552%7C5184001%7CSun%2C+23-Jul-2023+13%3A05%3A53+GMT; uid_tt=3c067674a5659d1c15be099916d0fd6c; sid_tt=f2d61b706ab7edbebfbe94465cbb185a; sessionid=f2d61b706ab7edbebfbe94465cbb185a; sid_ucp_v1=1.0.0-KGExMjhkNjViMzEzMGQ4NjVmZGFmMmQzZGMwODgyZGQ5MzU3NWZkMjkKGQjOp_CHgvTGBBCwl7ijBhjPCSAMOAJA8QcaAmxmIiBmMmQ2MWI3MDZhYjdlZGJlYmZiZTk0NDY1Y2JiMTg1YQ; ssid_ucp_v1=1.0.0-KGExMjhkNjViMzEzMGQ4NjVmZGFmMmQzZGMwODgyZGQ5MzU3NWZkMjkKGQjOp_CHgvTGBBCwl7ijBhjPCSAMOAJA8QcaAmxmIiBmMmQ2MWI3MDZhYjdlZGJlYmZiZTk0NDY1Y2JiMTg1YQ; store-region=cn-fj; store-region-src=uid; ttcid=21dbda5cc2664ba99d3c3c2c5dba91b079; tt_webid=7231811825317987898; odin_tt=09b0d9f947d795ecea86f41e4b5cad47d97a97007e0a6f17c7e42744e74b40c86c204c3bd31b1271f75914586eb78154; _S_WIN_WH=1536_722; _S_DPR=1.25; _S_IPAD=0; notRedShot=1; gftoken=ZjJkNjFiNzA2YXwxNjg0OTM3Njg1MzZ8fDAGBgYGBgY; _ga_1Y7TBPV8DE=GS1.1.1685069037.4.1.1685071827.0.0.0; _ga=GA1.1.826492488.1684933884; _ga_QEHZPBE5HH=GS1.1.1685098697.5.1.1685099433.0.0.0; uid_tt_ss=b617f3025557af16309989f19e52b216; sessionid_ss=5181c275b2d91edbddb3f7369ce4fb5e; csrf_session_id=6ac1a5f6821f9f44eb38435589962924; ttwid=1%7CwW844yKlt9XhyPHsNL44XIFR5k08cB-9PK2l14cMg8s%7C1685236077%7C03504f754d3d79d470e21fa0b40908b47ab2b5e84af31c5166a4b3fd4dcbab88; tt_scid=V8uUAwRtoyOyrp3gPj0g0YXRGn.A2MMS707LEUzrF-WYdZZDhu9R.7kaluEAcVRC2874; msToken=D6RHNqL61P2UvxX8h3uq993Ke76KKuoj17a9SsRytTkpYGhCDyOdytKgIXfs6D-9yzDQTlYGlOhIcrkDIREwwJUNoGQJkqPNUAK3wnXFecQ29GWE5CCN2Q==; msToken=SqBOe8uyY_4VVxTiHgzPkybXNcQ5GjzgnciXUTETBp5DC05bJpn_kcS1y1yU1qqSDQ_50GMR6CC8JgqHkxk6YBfU-q3xbzyHN-RE-k3UiNOTuZrCYAb9cw==";
            string url = "https://mp.toutiao.com/profile_v4/graphic/publish";

            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl(url);

            Thread.Sleep(1000);
           
            if (driver.Url.Contains("auth/page/login"))
            {
                //头条登陆
                driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__footer > div > ul > li:nth-child(4) > span")).Click();
                driver.FindElement(By.Name("normal-input")).SendKeys("15805935371");//账号
                driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-confirm-info > span.web-login-confirm-info__checkbox"))
                    .Click();//勾选复选框
                driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-account-password__password-input-wrapper > div > div > input"))
                    .SendKeys("Xwy1298630969");//密码

                driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-account-password__button-wrapper > button"))
                    .Click();//点击登陆

                while (true)
                {
                    if (driver.Url.Contains("auth/page/login"))
                    {
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        break;
                    }
                    
                }
                
            }

            
            
            if (driver.Url.Contains("graphic/publish"))
            {
                
                //发布文章
                try
                {
                    //是否继续编辑按钮
                    driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.publish-draft-tip-wrapper > div > div.draft-content > div"))
                   .Click();
                }
                catch (Exception)
                {

                    
                }
                string filePath = @"E:\工作区-文档\项目2023-正思考-心理-头条号运营\文章\5月28日\硬核理念：高效学习的核心方法！.txt";
                if (File.Exists(filePath))
                {
                    string title =Path.GetFileNameWithoutExtension(filePath);
                    driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.publish-editor-title-wrapper > div > div > div.title-wrapper > div > div > div > textarea"))
                    .SendKeys(title);//输入标题
                    string content = File.ReadAllText(filePath);
                    driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.syl-editor-wrap > div > div.ProseMirror"))
                        .SendKeys(content);//输入文章内容
                    Thread.Sleep(2000);
                    driver.FindElement(By.CssSelector("#masterRoot > div > div.pgc-content > section > main > div.menu-tab-stick-header-wrapper.menu-tab-wrapper-base_creation > div > svg"))
                        .Click();//返回主页
                }               
                
            }




            //IWebElement element = driver.FindElement(By.Id("kw"));
            //element.SendKeys("中国人");
            //driver.Close();


            //// 初始化 Chrome 驱动
            //IWebDriver driver = new ChromeDriver();

            //// 打开头条号登录页面
            //driver.Navigate().GoToUrl("https://mp.toutiao.com/profile_v3/index");

            //// 输入账号密码并登录
            //Thread.Sleep(5000);
            //driver.FindElement(By.XPath("//*[@id=\"BD_Login_Form\"]/div/article/article/div[2]/div/ul/li[4]/span")).Click();
            ////driver.FindElement(By.Name("account")).SendKeys("你的头条号账号");
            ////driver.FindElement(By.Name("password")).SendKeys("你的头条号密码");
            ////driver.FindElement(By.ClassName("submit")).Click();

            //// 等待页面加载
            //Thread.Sleep(5000);

            //// 跳转到发布文章页面
            //driver.Navigate().GoToUrl("https://mp.toutiao.com/create_article_v2/?source=mp&type=&is_edit_series=0&group_id=");

            //// 输入文章标题、正文和封面图
            //driver.FindElement(By.Name("title")).SendKeys("这是一篇测试文章");
            //driver.FindElement(By.ClassName("ProseMirror")).SendKeys("这是文章内容，你可以在这里输入任何你想写的内容。");
            //driver.FindElement(By.Name("cover")).SendKeys("封面图.jpg");

            //// 点击发布按钮
            //driver.FindElement(By.ClassName("save-btn")).Click();

            //// 关闭浏览器
            //driver.Quit();

            //writeLine("文章发布成功！");
            //Console.ReadKey();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //下面代码的代码展示这了两个方法的用法和用途。
            //1.打开百度首页，单击“注册”超级链接。
            //2.在弹出的窗口（百度账户注册）中，调用Close（）方法，关闭新弹出的页面
            //3.再一次点击“注册”超级链接，调用Quit（）方法来结束测试。
            //var service = EdgeDriverService.CreateDefaultService(@".", "msedgedriver.exe");
            IWebDriver driver = new ChromeDriver();

            //导航到百度首页
            driver.Navigate().GoToUrl("http://www.baidu.com");

            //进行点击
            writeLine("-------------------");
            writeLine("进行点击");
            driver.FindElement(By.LinkText("登录")).Click();
            System.Threading.Thread.Sleep(3 * 1000);
            driver.FindElement(By.LinkText("立即注册")).Click();

            //获取窗口句柄
            IList<string> listHand = driver.WindowHandles;

            //切换到注册窗口并关闭
            writeLine("-------------------");
            writeLine("切换到注册窗口");
            driver.SwitchTo().Window(listHand[1]);
            System.Threading.Thread.Sleep(3 * 1000);
            writeLine("-------------------");
            writeLine("关闭注册窗口");
            driver.Close();
            System.Threading.Thread.Sleep(3 * 1000);

            //切换到主窗口并结束测试
            writeLine("-------------------");
            writeLine("切换到主窗口并结束测试");
            driver.SwitchTo().Window(listHand[0]);
            driver.FindElement(By.LinkText("立即注册")).Click();
            System.Threading.Thread.Sleep(3 * 1000);
            driver.Quit();

            Console.ReadLine();
        }

        void writeLine(string str)
        {
            textBox1.Text += str + "\r\n";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://www.baidu.com");

            //获取Cookie
            ICookieJar listCookie = driver.Manage().Cookies;
            // IList listCookie = driver.Manage( ).Cookies.AllCookies;//只是显示 可以用Ilist对象
            //显示初始Cookie的内容
            writeLine("--------------------");
            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");
            for (int i = 0; i < listCookie.AllCookies.Count; i++)
            {

                writeLine($"Cookie的名称:{listCookie.AllCookies[i].Name}");
                writeLine($"Cookie的值:{listCookie.AllCookies[i].Value}");
                writeLine($"Cookie的所在域:{listCookie.AllCookies[i].Domain}");
                writeLine($"Cookie的路径:{listCookie.AllCookies[i].Path}");
                writeLine($"Cookie的过期时间:{listCookie.AllCookies[i].Expiry}");
                writeLine("-----");
            }


            //添加一个新的Cookie
            Cookie newCookie = new Cookie("新Cookie", "新值", "", DateTime.Now.AddDays(1));

            listCookie.AddCookie(newCookie);
            writeLine("--------------------");
            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");
            for (int i = 0; i < listCookie.AllCookies.Count; i++)
            {

                writeLine($"Cookie的名称:{listCookie.AllCookies[i].Name}");
                writeLine($"Cookie的值:{listCookie.AllCookies[i].Value}");
                writeLine($"Cookie的所在域:{listCookie.AllCookies[i].Domain}");
                writeLine($"Cookie的路径:{listCookie.AllCookies[i].Path}");
                writeLine($"Cookie的过期时间:{listCookie.AllCookies[i].Expiry}");
                writeLine("-----");
            }

            //删除这个Cookie并再次显示总数
            listCookie.DeleteCookieNamed(newCookie.Name);

            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");





            driver.Navigate().GoToUrl("https://blog.csdn.net/yangyong1250/article/details/128892399");

            //获取Cookie
            listCookie = driver.Manage().Cookies;
            // IList listCookie = driver.Manage( ).Cookies.AllCookies;//只是显示 可以用Ilist对象
            //显示初始Cookie的内容
            writeLine("--------------------");
            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");
            for (int i = 0; i < listCookie.AllCookies.Count; i++)
            {

                writeLine($"Cookie的名称:{listCookie.AllCookies[i].Name}");
                writeLine($"Cookie的值:{listCookie.AllCookies[i].Value}");
                writeLine($"Cookie的所在域:{listCookie.AllCookies[i].Domain}");
                writeLine($"Cookie的路径:{listCookie.AllCookies[i].Path}");
                writeLine($"Cookie的过期时间:{listCookie.AllCookies[i].Expiry}");
                writeLine("-----");
            }


            //添加一个新的Cookie
            newCookie = new Cookie("新Cookie", "新值", "", DateTime.Now.AddDays(1));

            listCookie.AddCookie(newCookie);
            writeLine("--------------------");
            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");
            for (int i = 0; i < listCookie.AllCookies.Count; i++)
            {

                writeLine($"Cookie的名称:{listCookie.AllCookies[i].Name}");
                writeLine($"Cookie的值:{listCookie.AllCookies[i].Value}");
                writeLine($"Cookie的所在域:{listCookie.AllCookies[i].Domain}");
                writeLine($"Cookie的路径:{listCookie.AllCookies[i].Path}");
                writeLine($"Cookie的过期时间:{listCookie.AllCookies[i].Expiry}");
                writeLine("-----");
            }

            //删除这个Cookie并再次显示总数
            listCookie.DeleteCookieNamed(newCookie.Name);

            writeLine($"当前Cookie集合的数量：\t{listCookie.AllCookies.Count}");


            //Console.ReadLine();
            driver.Quit();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ChromeOptions options = new ChromeOptions();

            // 设置代理服务器地址、端口、用户名和密码
            options.AddArgument("--proxy-server=www.16yun.cn:31111");
            options.AddArgument("--proxy-username=16ip");
            options.AddArgument("--proxy-password=16ps");

            // 启用无头模式
            options.AddArgument("--headless");

            // 加载Chrome扩展，用于自动填充认证窗口
            options.AddExtension("auth_ext.crx");

            // 创建ChromeDriver实例
            IWebDriver driver = new ChromeDriver(options);

            // 访问需要认证的网页
            driver.Navigate().GoToUrl("https://www.amazon.com/");

            //// 等待认证窗口出现并自动填充
            //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            //wait.Until(ExpectedConditions.AlertIsPresent());
            //IAlert alert = driver.SwitchTo().Alert();
            //alert.SetAuthenticationCredentials("username", "password");
            //alert.Accept();

            // 关闭浏览器
            driver.Quit();
        }
    }
}
